--- title: Static Plots keywords: fastai sidebar: home_sidebar summary: "All types of plots in matplotlib are included in this module. This includes bands,DOS and other general plots, which can be saved as pdf,png,jpg and other formats that matplotlib offers." description: "All types of plots in matplotlib are included in this module. This includes bands,DOS and other general plots, which can be saved as pdf,png,jpg and other formats that matplotlib offers." nb_path: "StaticPlots.ipynb" ---
{% raw %}
{% endraw %} {% raw %}

  Index 
  XmlElementTree 
  StaticPlots● 
  InteractivePlots 
  Utilities 
  StructureIO 
  Widgets 

{% endraw %}

Passing Large Number of Arguments as a Dictionary

  • Let's take example of plot_bands. It requires 10 arguments and most of them are default, but in order to tweak parameters, you still need to access them. Follow These steps to input arguments easily.
  • In code cell, write plot_bands? and hit enter. This will give Signature and DocString.
  • Copy arguments and pass to a dictionary dict(what you copied). In a Jupyter Notebook cell, you can edit it:
{% raw %}
arg_dict=dict(
    ax=None,
    kpath=None,
    bands=None,
    showlegend=True,
    E_Fermi=0,
    color1=(1, 0, 0.8),
    style1='solid',
    lw1=0.7,
    )
arg_dict
{'ax': None,
 'kpath': None,
 'bands': None,
 'showlegend': True,
 'E_Fermi': 0,
 'color1': (1, 0, 0.8),
 'style1': 'solid',
 'lw1': 0.7}
{% endraw %}
  • As you can see, I deleted few unnecessary arguments. Now you can use dictionary unpacking operator ** inside function, it will pass all arguments present in dictionary. Make sure you do not change name of variables, although you can delete as few of them.
  • Usage: Call function as plot_bands(**arg_dict). You can edit dictionary on fly, or can save it to a file to read (Not recommended, could be a threat to your system security as reading dictionaries from a file could run potentially harmful commands as well.)

Simple Band Struture Plots

{% raw %}

plot_bands[source]

plot_bands(ax=None, kpath=None, bands=None, showlegend=False, E_Fermi=None, color1=(0, 0, 0.8), style1='solid', lw1=0.7, color2=(0.8, 0, 0), style2='dashed', lw2=0.7)

  • Returns axes object and plot on which all matplotlib allowed actions could be performed.
  • Parameters
    • ax : Matplotlib axes object, if not given, one is created.
    • kpath : 1D array from get_kpts().kpath or export_vasprun().kpath.
    • bands : Dictionary Object from get_evals or export_vasprun().bands.
    • showlegend : Boolean, default is False, if true, gives legend for spin-polarized calculations.
    • E_Fermi : If not given, automatically picked from bands object.
    • **kwargs : lines color,width and style to distinguish spin Up and Down.
  • Returns
    • ax : matplotlib axes object with plotted bands.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

modify_axes[source]

modify_axes(ax=None, xticks=[], xt_labels=[], xlim=[], yticks=[], yt_labels=[], ylim=[], xlabel=None, ylabel=None, vlines=True, zeroline=True)

  • Returns None, applies given settings on axes. Prefered to use before other plotting.
  • Parameters
    • ax : Matplotlib axes object.
    • (x,y)ticks : List of positions on (x,y axes).
    • (xt,yt)_labels : List of labels on (x,y) ticks points.
    • (x,y)lim : [min, max] of (x,y) axes.
    • (x,y)label : axes labels.
    • vlines : If true, drawn when ylim is not empty.
    • zeroline : If True, drawn when xlim is not empty.
{% endraw %} {% raw %}
{% endraw %}

Working in object-oriented way, we can have plenty of options in matplotlib. See the example below, which provides an overview of flexibility of matplotlib. All functions are defined in object-oriented way for better compatibility and flexibility.

Example: Graphene

{% raw %}
import pivotpy.vr_parser as vp
vr1=vp.export_vasprun(path=f1)
vr2=vp.export_vasprun(path=f2)
import pivotpy.s_plots as sp
import matplotlib.pyplot as plt

fig,ax=plt.subplots(1,3,figsize=(10.2,2.6),sharey=True)
ax0=sp.plot_bands(ax=ax[0],kpath=vr2.kpath,bands=vr2.bands,showlegend=True)

ax1=sp.plot_bands(ax=ax[1],kpath=vr1.kpath,bands=vr1.bands,color1='y')

ax2=sp.plot_bands(ax=ax[2],kpath=vr1.kpath,bands=vr1.bands,color1='y')
ax2=sp.plot_bands(ax=ax[2],kpath=vr2.kpath,bands=vr2.bands,showlegend=True)
xticks=[vr1.kpath[i] for i in [0,30,60,-1]]
txts=["Polarized","Unpolarized","Comparison"]
for axes,txt in zip(ax,txts):
    if axes==ax0:
        sp.modify_axes(ax=axes,ylabel='Energy (eV)')
    sp.modify_axes(ax=axes,ylim=[-10,10],xlim=[xticks[0],xticks[-1]],xticks=xticks,xt_labels=[r'$\Gamma$','M','K',r'$\Gamma$'])
    axes.text(0.05,0.9,txt,bbox=dict(edgecolor='white',facecolor='white', alpha=0.9),transform=axes.transAxes,color='red')
plt.subplots_adjust(hspace=0.01,wspace=0.05)
{% endraw %} {% raw %}

quick_bplot[source]

quick_bplot(path_evr=None, ax=None, skipk=None, joinPathAt=[], elim=[], xt_indices=[], xt_labels=[], E_Fermi=None, figsize=(3.4, 2.6), txt=None, xytxt=[0.05, 0.9], ctxt='black')

  • Returns axes object and plot on which all matplotlib allowed actions could be performed.
  • Parameters
    • path_evr : path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • ax : Matplotlib axes object, if not given, one is created.
    • skipk : Number of kpoints to skip, default will be from IBZKPT.
    • joinPathAt : Points where kpath is broken.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • xt_indices : High symmetry kpoints indices.abs
    • xt_labels : High Symmetry kpoints labels.
    • **kwargs : figsize=(3.4,2.6). Text,its position and color.
  • Returns
    • ax : matplotlib axes object with plotted bands.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

add_text[source]

add_text(ax=None, xs=0.05, ys=0.9, txts='[List]', colors='r')

  • Adds text entries on axes, given single string or list.
  • Parameters
    • xs : List of x coordinates relative to axes or single coordinate.
    • ys : List of y coordinates relative to axes or single coordinate.
    • txts : List of strings or one string.
    • colors: List of x colors of txts or one color.
{% endraw %} {% raw %}
{% endraw %}

Below is example where you can add multiple text entries on a quick_bplot.

{% raw %}
ax=sp.quick_bplot(path_evr=f2,elim=[-5,5],xt_indices=[0,30,60,-1],xt_labels=['W','K',''],txt='Graphene',ctxt='r')
sp.add_text(ax=ax,xs=[0.35,0.5],ys=[0.55,0.7],txts=[r'$E_{gap}$ = 0 eV','edge states'],colors=['red','blue'])
{% endraw %} {% raw %}

add_legend[source]

add_legend(ax=None, colors=[], labels=[], styles='solid', widths=0.7, anchor=(0, 1), ncol=3, loc='lower left', fontsize='small', frameon=False, **legend_kwargs)

  • Adds custom legeneds on a given axes,returns None.
  • Parameters
    • ax : Matplotlib axes.
    • colors : List of colors.
    • labels : List of labels.
    • styles : str or list of line styles.
    • widths : str or list of line widths.
    • **kwargs : Matplotlib's legend arguments.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

add_colorbar[source]

add_colorbar(ax=None, colors=[], N=256, scales=[1, 1, 1], ticks=[0.16666666666666666, 0.5, 0.8333333333333334], ticklabels=['r', 'g', 'b'], vertical=False, fontsize=8)

  • Plots colorbar on a given axes. This axes should be only for colorbar. Returns None but registers a color map _hsv_ in matplotlib.
  • Parameters
    • ax : Matplotlib axes object.
    • colors : List of colors in colorbar, if not given, RGB colorbar is added.
    • N : int, number of color points Default 256.
    • scales : List of 3 numbers in interval [0,1] to scale colors.
    • ticks : List of tick values to show on colorbar in interval [0,1].
    • ticklabels : List of labels for ticks.
    • vertical : Boolean, default is Fasle.
    • fontsize : Default 8. Adjustable according to plot space.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
import pivotpy.s_plots as sp
import matplotlib.pyplot as plt 
plt.style.use('dark_background')
fig,ax=plt.subplots(1,2,figsize=(9,1))
add_colorbar(ax=ax[0],vertical=True,N=7)
add_colorbar(ax=ax[1],scales=[0.9,0.9,0.9],N=21)
{% endraw %}

Including Atomic and Orbital Projections

{% raw %}

create_rgb_lines[source]

create_rgb_lines(ax=None, kpath=None, evals_set=None, pros_set=None, ions=[0], orbs=[[0], [], []], labels=['', '', ''], uni_width=False, max_width=2.5, uni_color=False, color='red', interpolate=False, n=5, k=3, scale_color=False)

  • Plot on a given axes or returns line collection, lines and colors if axes is None, which can be added to an ax only onces,by using ax.add_collection(collection) and then ax.autoscale_view() will make it visible.
  • Parameters
    • ax : Matplotlib axes object, if not given, linecollection is returned.
    • kapath : export_vasprun().kpath or get_kpts().kpath.
    • evals_set: export_vasprun().bands.evals or get_evals().evals. If calculations are spin-polarized, it will be ...evals.SpinUp/SpinDown for both. You need to create collections twice for SpinUp and SpinDown separately.
    • pros_set : export_vasprun().pro_bands.pros or get_bands_pro_set().pros. If calculations are spin-polarized, it will be ...pros.SpinUp/SpinDown for both. You need to create collections twice for SpinUp and SpinDown separately.
    • ions : List of ions to project on, could be range(start,stop,step) as well, remember that stop is not included in python. so range(0,2) will generate 0 and 1 indices.
    • orbs : List of three lists of orbitals indices. [[red],[green],[blue]], you can create any color by this combination. For example, to get s-orbital in yellow color, you will use [[0],[0],[]]. Do not remove empty list from there, it will not effect your orbital selection.
    • uni_width: If True, will keep equal width=max_width/2 of lines.
    • max_width: Default is 5. Orbitals' projections are added and Normalized to this thickness.
    • uni_color: If True, will not change color in a band from point to point,width is reduced.
    • color : (str,rgb,rgba), if uni_color=True, color will be applied to line.
    • interpolate: Deafult is false, if True, it will add n points between nearest kpoints.
    • n : int, default is 5. Adds n points between nearest kpoints.
    • k : int, order of interpolation, defualt is 3. n > k should be hold.
    • scale_color: If True, colors are scaled to 1 at each points.
  • Returns
    • line collection : Matplotlib line collection object.
    • line patches : An (N,2,2) dimensional arry.
    • colors : An (N,4) or (N,3) dimensional list.(Not scaled.)
  • Exception
    • If uni_color and uni_width are True together, this leads to simple plot. No collections will be created. Use bands_plot() instead.
{% endraw %} {% raw %}
{% endraw %}

Using create_rgb_line in object oriented way.

  • The below example let's user know how to connect pieces of objects to create a complex figure. Note that in case of adding multiple collections on an axes,(left figure),what you see depends on what was the order of adding collections on each other. Also multiple lines are automatically normalized to real data if they have same max_width, so you can compare, say, s line and p line with each other.
{% raw %}
import time
start=time.time()
import numpy as np 
import pivotpy.vr_parser as vp
path='E:/Research/graphene_example/ISPIN_2/bands/vasprun.xml'
vr=vp.export_vasprun(path=path,elim=[-10,10])
k=vr.kpath
ef=vr.tdos.E_Fermi
en=vr.bands.evals.SpinUp-ef
pros=vr.pro_bands.pros.SpinUp
Loading from PowerShell Exported Data...
{% endraw %} {% raw %}
import pivotpy.s_plots as sp 
import matplotlib.pyplot as plt 
fig1,ax = plt.subplots(1,3,figsize=(10.2,2.6),sharey=True)
axc     = fig1.add_axes([0.5,1,0.3,0.04])
C1      = range(0,1)
spd     = [[0],[1],[2,3]]
sp.create_rgb_lines(ax=ax[0],kpath=k,evals_set=en,pros_set=pros,interpolate=True,n=15,uni_color=True,orbs=[[0],[0],[0]],ions=C1)
sp.create_rgb_lines(ax=ax[0],kpath=k,evals_set=en,pros_set=pros,\
        uni_color=True,color=(0,1,0,1),orbs=[[],[1],[]],ions=C1)
sp.create_rgb_lines(ax=ax[0],kpath=k,evals_set=en,pros_set=pros,uni_color=True,color=(0,0,1,0.4),orbs=[[],[],[2,3]],ions=C1)
sp.create_rgb_lines(ax=ax[1],kpath=k,evals_set=en,pros_set=pros,orbs=spd,ions=C1)
sp.create_rgb_lines(ax=ax[2],kpath=k,evals_set=en,pros_set=pros,\
        uni_width=True,orbs=spd,ions=C1)
[sp.modify_axes(ax=axes) for axes in ax]
sp.add_legend(ax=ax[0],labels=['C-s','C-pz','C-px+py'],widths=4)
sp.add_colorbar(ax=axc,colors=[(1,0,0),(0,1,0),(0,0,1)],ticklabels=['C-s','C-pz','C-px+py'],ticks=[0,0.5,1])
plt.subplots_adjust(wspace=0.05)
txts=['uni_color=True','variable width/color','uni_width=True']
[sp.add_text(ax=axes,txts=txt) for axes,txt in zip(ax,txts)];
print('Executed in {} seconds.'.format(time.time()-start))
No handles with labels found to put in legend.
Executed in 49.004796504974365 seconds.
{% endraw %} {% raw %}

quick_rgb_lines[source]

quick_rgb_lines(path_evr=None, ax=None, skipk=None, joinPathAt=[], elim=[], elements=[[0], [], []], orbs=[[0], [], []], labels=['Elem0-s', '', ''], max_width=2.5, xt_indices=[0, -1], xt_labels=['$\\Gamma$', 'M'], E_Fermi=None, figsize=(3.4, 2.6), txt=None, xytxt=[0.05, 0.9], ctxt='black', uni_width=False, interpolate=False, spin='both', n=5, k=3, scale_color=True, colorbar=True, color_matrix=None)

  • Returns axes object and plot on which all matplotlib allowed actions could be performed. In this function,orbs,labels,elements all have list of length 3. Inside list, sublists or strings could be any length but should be there even if empty.
  • Parameters
    • path_evr : path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • ax : Matplotlib axes object, if not given, one is created.
    • skipk : Number of kpoints to skip, default will be from IBZKPT.
    • joinPathAt : Points where kpath is broken.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • xt_indices : High symmetry kpoints indices.abs
    • xt_labels : High Symmetry kpoints labels.
    • elements : List [[0],[],[]] by default and plots s orbital of first ion..
    • orbs : List [[r],[g],[b]] of indices of orbitals, could be empty, but shape should be same.
    • labels : List [str,str,str] of projection labels. empty string should exist to maintain shape. Auto adds , for ISPIN=2.
    • max_width : Width to scale whole projections. if uni_width=True, width=max_width/2.
    • figsize : Tuple (width,height) in inches. Default (3.4.2.6) is article column's width.
    • txt : Text on figure, if None, SYSTEM's name is printed.
    • xytxt : [x_coord,y_coord] of text relative to axes.
    • ctxt : color of text.
    • uni_width : If True, width of bands kept uniform.
    • uni_color : If True, color of bands kept same.
    • color : (str,rgb,rgba), if uni_color=True, color is applied.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interpolate: Default is False, if True, bands are interpolated.
    • n : int, number of points, default is 5.
    • k : int, order of interpolation 0,1,2,3. Defualt 3. n > k should be hold.
    • scale_color: Boolean. Default True, colors are scaled to 1 at each point.
    • colorbar : Default is True. Displays a vertical RGB colorbar.
    • color_matrix: Only works if scale_color==True. 3x3 numpy array or list to transform from RGB to another space,sum of each row element should be <= 1. For simply changing the color intensity use np.diag([r,g,b]) with r,g,b interval in [0,1]. Try pivotpy.color(gray)_matrix as suggested color matrix and modify!
  • Returns
    • ax : matplotlib axes object with plotted projected bands.
    • Registers as colormap RGB_m to use in DOS to plot in same colors.
{% endraw %} {% raw %}
{% endraw %}
  • quick_rgb_lines() is waraper around create_rgb_lines(uni_color=False). You can pass lists for orbs,labels,colors and elements eeach of length 3 with one axis.
    • If you do not provide any arguemnts, this will create graph of whole system projections over s,p,d orbitals.
    • elements argument is special, you can pass index of element which will pick all ions of that type, or list(length=3) of indices of ions, e.g in elements=[0,[0,1],2] of system Ga32As31Bi1, 0 and 2 pick all ions of Ga and Bi respectively, while [0,1] will pick first two ions of Ga.
    • If scale_color=True, ecah point on plot is scaled to maximum color, if False, whole plot is scaled.
    • color_matrix is to convert between color spaces and play around as you can. Sum of each row should be less than or equal to 1. Only works if scale_color=True. {% include tip.html content='Gray scale matrix = pivotpy.gray_matrix and kind of body centered cubic matrix = pivotpy.color_matrix.' %}
{% raw %}
import os
import numpy as np
os.chdir('E:/Research/graphene_example/ISPIN_2/bands')
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import pivotpy as pp
labels=['s','p$_z$','p$_x$+p$_y$']
axs=pp.init_figure(nrows=2,ncols=3,figsize=(9,5),sharex=True,sharey=True);
quick_rgb_lines(ax=axs[0,0],elements=[0,[0,1],[0,1]],orbs=[0,[1],[2,3]],spin='up',txt='scale_color=False',colorbar=True,labels=labels,scale_color=False)
quick_rgb_lines(ax=axs[0,1],elements=[0,[0,1],[0,1]],orbs=[0,[1],[2,3]],spin='down',txt='Intensity reduced',colorbar=True,labels=labels,color_matrix=np.diag([0.5,0.7,0.5]))
quick_rgb_lines(ax=axs[0,2],elements=[0,[0,1],[0,1]],orbs=[0,[1],[2,3]],spin='both',txt='scale_color=True',colorbar=True,labels=labels)

plt.style.use(['default','seaborn'])
_ = quick_rgb_lines(ax=axs[1,0],elements=[0,[0,1],[0,1]],orbs=[0,[2],[1,3]],spin='up',txt='color_matrix',colorbar=True,labels=labels,color_matrix=pp.color_matrix)
_ = quick_rgb_lines(ax=axs[1,1],elements=[0,[0,1],[0,1]],orbs=[0,[2],[1,3]],spin='down',txt='color_matrix.T',colorbar=True,labels=labels,color_matrix=pp.color_matrix.T)
_ = quick_rgb_lines(ax=axs[1,2],elements=[0,[0,1],[0,1]],orbs=[0,[2],[1,3]],spin='both',txt='gray_matrix',colorbar=True,labels=labels,color_matrix=[[0.3  , 0.59  , 0.11],[0.3  , 0.59  , 0.11],[0.3  , 0.59  , 0.11]])
{% endraw %}
  • See below the colormap RGB_m represents the last axes of the above figure. This is useful to dirctly use in DOS plot to get same colors as bands.
{% raw %}
plt.style.use(['default'])
x = np.linspace(0,1,256)
x = np.vstack((x,x))
x=plt.cm.get_cmap('RGB_m')(x)
plt.imshow(x)
<matplotlib.image.AxesImage at 0x25ef5483648>
{% endraw %} {% raw %}

quick_color_lines[source]

quick_color_lines(path_evr=None, axes=None, skipk=None, joinPathAt=[], elim=[], elements=[[0]], orbs=[[0]], labels=['s'], color_map='gist_rainbow', max_width=2.5, xt_indices=[0, -1], xt_labels=['$\\Gamma$', 'M'], E_Fermi=None, showlegend=True, figsize=(3.4, 2.6), txt=None, xytxt=[0.05, 0.85], ctxt='black', spin='both', interpolate=False, n=5, k=3, legend_kwargs={'ncol': 4, 'anchor': (0, 0.85), 'handletextpad': 0.5, 'handlelength': 1, 'fontsize': 'small', 'frameon': True}, **subplots_adjust_kwargs)

  • Returns axes object and plot on which all matplotlib allowed actions could be performed. If given, axes,elements,orbs colors, and labels must have same length. If not given, zeroth ion is plotted with s-orbital.
  • Parameters
    • path_evr : Path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • axes : Matplotlib axes object with one or many axes, if not given, auto created.
    • skipk : Number of kpoints to skip, default will be from IBZKPT.
    • joinPathAt : Points where kpath is broken.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • xt_indices : High symmetry kpoints indices.abs
    • xt_labels : High Symmetry kpoints labels.
    • elements : List [[0],], by defualt and plot first ion's projections.
    • orbs : List [[0],] lists of indices of orbitals, could be empty.
    • labels : List [str,] of orbitals labels. len(labels)==len(orbs) must hold. Auto adds , for ISPIN=2.
    • color_map : Matplotlib's standard color maps. Default is 'gist_ranibow'.
    • showlegend : True by defualt.
    • max_width : Width to scale whole projections. if uni_width=True, width=max_width/2.
    • figsize : Tuple (width,height) in inches. Default (3.4.2.6) is article column's width.
    • txt : Text on figure, if None, SYSTEM's name is printed.
    • xytxt : [x_coord,y_coord] of text relative to axes.
    • ctxt : color of text.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interpolate: Default is False, if True, bands are interpolated.
    • n : int, number of points, default is 5.
    • k : int, order of interpolation 0,1,2,3. Defualt 3. n > k should be hold.
    • legend_kwargs: Dictionary to contain legend arguments to fix.
    • **subplots_adjust_kwargs : plt.subplots_adjust parameters.
  • Returns
    • ax : matplotlib axes object with plotted projected bands.
{% endraw %} {% raw %}
{% endraw %}
  • quick_color_lines() is waraper around create_rgb_lines(uni_color=True,scale_color=False). You can pass equal length lists for orbs,labels, and elements either with one axis or mutltiple axes.
    • If you do not provide any arguemnts, this will plots-orbital of first ion.
    • elements argument is special, you can pass index of element which will pick all ions of that type, or list(length=3) of indices of ions, e.g in elements=[0,[0,1],2] of system Ga32As31Bi1, 0 and 2 pick all ions of Ga and Bi respectively, while [0,1] will pick first two ions of Ga.
    • If your given len(axis)=1, all projections are plotted on single axis and you can tweak opacity, legend display etc. There are plenty of options.

Colors Selection

Instead of giving custom colors, you can use matplotlib's colormaps to be consistent. Use

plt.colormaps()

to see list of available color maps. To get a color array from a map, you can do the following:

from matplotlib.pyplot import cm
colors  = cm.hsv(np.linspace(0,1,3))
# This will give you three colors from 'hsv' map.

Note: Two custom colormaps RGB,RGB_m are registered in session when you import pivotpy,which could be used when plotting DOS with bands of same color. RGB_m at any moment would represent the latest quick_rgb_lines.

{% raw %}
import os
path='E:/Research/graphene_example/ISPIN_2/bands'
os.chdir(path)
import pivotpy as pp
import matplotlib.pyplot as plt
axs=pp.init_figure(nrows=1,ncols=3,figsize=(7,2.5),sharey=True,sharex=True)
args_dict=dict(elements=[0,0,[0,1]],orbs=[0,1,[2]],labels=['s','$p_z$','$p_x$'],hspace=0.1,wspace=0.07,showlegend=True)
quick_color_lines(axes=axs[0],**args_dict,left=0.06,color_map='flag',spin='up');
quick_color_lines(axes=axs[1],**args_dict,left=0.06,color_map='FCC',spin='down');
quick_color_lines(axes=axs[2],**args_dict,left=0.06,color_map='RGB',spin='both');
{% endraw %}

Initializing Figure

{% raw %}

init_figure[source]

init_figure(figsize=(3.4, 2.6), nrows=1, ncols=1, widths=[], heights=[], axes_off=[], sharex=False, sharey=False, **subplots_adjust_kwargs)

  • Returns all axes of initialized figure, based on plt.subplots().
  • Parameters
    • figsize : Tuple (width, height). Default is (3.4,2.6).
    • nrows : Default 1.
    • ncols : Default 1.
    • widths : List with len(widths)==nrows, to set width ratios of subplots.
    • heights : List with len(heights)==ncols, to set height ratios of subplots.
    • share(x,y): Share axes between plots, this removes shared ticks automatically.
    • axes_off : Turn off axes visibility, If nrows = ncols = 1, set True/False, If anyone of nrows or ncols > 1, provide list of axes indices to turn off. If both nrows and ncols > 1, provide list of tuples (x_index,y_index) of axes.
    • **subplots_adjust_kwargs : These are same as plt.subplots_adjust()'s arguements.
{% endraw %} {% raw %}
{% endraw %}

Tweaking init_figure by using gridspec.

  • This is a powerful way yo include any type of grid. For this, first use gs = axs[0,0].get_gridspec() and then remove axes you want to replace for another shape, then add required axis by plt.gcf().add_subplot(gs[x_ind, y_ind]). This process is illustrated in below examples.
  • Soft Tweaking
    • Axes remain same, just widths and height ratios are chnaged.
{% raw %}
import pivotpy.s_plots as sp 
axs=sp.init_figure(figsize=(3.4,2.6),ncols=3,widths=[3.4,1,3.4],nrows=3,heights=[2.6,1,2.6],wspace=0.076,hspace=0.1)
[[sp.modify_axes(ax=a,xticks=[0],yticks=[0]) for a in ax] for ax in axs]
[sp.add_colorbar(ax=ax,ticks=[]) for ax in [axs[1,0],axs[1,2]]];
[sp.add_colorbar(ax=ax,vertical=True,ticks=[]) for ax in [axs[0,1],axs[2,1]]];
{% endraw %}
  • Brute Force Tweaking
    • Here we will remove and regenerate axes based on our grid choice.
{% raw %}
axs=sp.init_figure(figsize=(5,3.4),nrows=3,ncols=2,widths=[1,1],heights=[1,7,7],wspace=0.4,hspace=0.4,axes_off=[(2,0)],sharex=True,sharey=True)
import pivotpy.s_plots as sp 
import matplotlib.pyplot as plt
gs = axs[0,0].get_gridspec()
axs_to_remove=[*axs[0, :],*axs[1:, 1]]
for ax in axs_to_remove:
    ax.remove()
axlarge = plt.gcf().add_subplot(gs[0, :])
axv = plt.gcf().add_subplot(gs[1:, 1])
sp.modify_axes(ax=axv)
sp.add_colorbar(ax=axlarge)
sp.add_text(ax=axs[1,0],txts='axis[1,0]',xs=0.25,ys=0.5)
sp.add_text(ax=axs[2,0],txts='axis[2,0] is off',xs=0.15,ys=0.5)
import pivotpy.vr_parser as vp 
vr=vp.export_vasprun(path='E:/Research/graphene_example/ISPIN_1/bands/vasprun.xml')
sp.quick_bplot(path_evr=vr,ax=axv,txt='Plotting',E_Fermi=10)
sp.add_text(ax=axv,txts='BigAxes',xs=0.25,ys=0.5)
{% endraw %}
  • Mixing 2D and 3D axes in a figure
    • A minial example below shows deleting an axes and then adding a 3D axes with same dimensions.
{% raw %}
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt 
import pivotpy as pp 
ax = pp.init_figure(nrows=2,ncols=2,widths=[1,2],heights=[1,2])
pos = ax[1,1].get_position()
ax[1,1].remove()
ax[1,1]=plt.gcf().add_axes(pos,projection='3d')
{% endraw %}

Plotting Density of States

{% raw %}

select_pdos[source]

select_pdos(tdos=None, pdos_set=None, ions=[0], orbs=[0], E_Fermi=0, interpolate=False, n=5, k=3)

  • Returns (interpolated/orginal) enrgy(N,), tdos(N,), and pdos(N,) of selected ions/orbitals.
  • Parameters
    • tdos : export_vasprun().tdos or get_tdos().tdos. If calculations are spin-polarized, it will be ..tdos.SpinUp/SpinDown for both. You need to apply this function twice for SpinUp and SpinDown separately.
    • pdos_set : export_vasprun().pro_dos.pros or get_dos_pro_set().pros. If calculations are spin-polarized, it will be ...pros.SpinUp/SpinDown for both.
    • ions : List of ions to project on, could be range(start,stop,step) as well, remember that stop is not included in python. so range(0,2) will generate 0 and 1 indices.
    • orbs : List of orbitals indices to pick.
    • E_Fermi : Here it is zero. Needs to be input.
    • interpolate: Deafult is false, if True, it will add n points between nearest points.
    • n : int, default is 5. Adds n points between nearest kpoints.
    • k : int, order of interpolation, defualt is 3. n > k should be hold.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

collect_dos[source]

collect_dos(path_evr=None, elim=[], elements=[[0]], orbs=[[0]], labels=['s'], E_Fermi=None, spin='both', interpolate=False, n=5, k=3)

  • Returns lists of energy,tdos, pdos and labels. If given,elements,orbs and labels must have same length. If not given, zeroth ions is collected with s-orbital.
  • Parameters)
    • path_evr : Path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • elements : List [[0],], by defualt and plot first ion's projections.
    • orbs : List [[0],] lists of indices of orbitals, could be empty.
    • labels : List [str,] of orbitals labels. len(labels)==len(orbs) must hold. Auto adds , for ISPIN=2.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interpolate: Default is False, if True, bands are interpolated.
    • n : int, number of points, default is 5.
    • k : int, order of interpolation 0,1,2,3. Defualt 3. n > k should be hold.
  • Returns
    • Energy : (N,1) size.
    • tdos : (N,1) size or [(N,1),(N,1)] if spin polarized.
    • pdos : [(N,1),(N,1),...], spin polarized is auto-fixed.
    • labels : ['label1,'label2',...] spin polarized is auto-fixed.
    • vr : Exported vasprun.
{% endraw %} {% raw %}
{% endraw %}
  • Providing labels while using collect_dos is important, it will automatically return spin up/down saymbols.
{% raw %}

quick_dos_lines[source]

quick_dos_lines(path_evr=None, ax=None, elim=[], include_dos='both', elements=[[0]], orbs=[[0]], labels=['s'], color_map='gist_rainbow', tdos_color=(0.8, 0.95, 0.8), linewidth=0.5, fill_area=True, vertical=False, E_Fermi=None, figsize=(3.4, 2.6), txt=None, xytxt=[0.05, 0.85], ctxt='black', spin='both', interpolate=False, n=5, k=3, showlegend=True, legend_kwargs={'ncol': 4, 'anchor': (0, 1), 'handletextpad': 0.5, 'handlelength': 1, 'fontsize': 'small', 'frameon': True})

  • Returns ax object (if ax!=False) and plot on which all matplotlib allowed actions could be performed, returns lists of energy,tdos and pdos and labels. If given,elements,orbs colors, and labels must have same length. If not given, zeroth ions is plotted with s-orbital.
  • Parameters)
    • path_evr : Path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • ax : Matplotlib axes object, if None, one is created. If False, data lists are returned.
    • include_dos: One of {'both','tdos','pdos'}.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • elements : List [[0],], by defualt and plot first ion's projections.
    • orbs : List [[0],] lists of indices of orbitals, could be empty.
    • labels : List [str,] of orbitals labels. len(labels)==len(orbs) must hold. Auto adds , for ISPIN=2.
    • color_map : Matplotlib's standard color maps. Default is 'gist_ranibow'. Use 'RGB' if want to compare with quick_rgb_lines with 3 projection inputs (len(orbs)==3).
    • fill_area : Default is True and plots filled area for dos. If False, plots lines only.
    • vertical : False, If True, plots along y-axis.
    • showlegend : True by defualt.
    • figsize : Tuple (width,height) in inches. Default (3.4.2.6) is article column's width.
    • txt : Text on figure, if None, SYSTEM's name is printed.
    • xytxt : [x_coord,y_coord] of text relative to axes.
    • ctxt : color of text.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interpolate: Default is False, if True, bands are interpolated.
    • n : int, number of points, default is 5.
    • k : int, order of interpolation 0,1,2,3. Defualt 3. n > k should be hold.
    • legend_kwargs: Dictionary to contain legend arguments to fix.
  • Returns
    • ax : Matplotlib axes.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
quick_dos_lines(path_evr='E:/Research/graphene_example/ISPIN_2/dos/vasprun.xml',vertical=False,fill_area=True,showlegend=True,include_dos='pdos',orbs=[[1,2,3],0,1],elements=[0,0,1],linewidth=1,labels=['p','s','g'],color_map='RGB',elim=[-5,5],spin='both')
<matplotlib.axes._subplots.AxesSubplot at 0x177114e8088>
{% endraw %}

High Display Image in Notebook

The function below plt_to_html is implemented for use in pivotpy-dash app to view and save SVG image directly from web app's interface. This also enables high display output in jupyter notebook.

{% raw %}

plt_to_html[source]

plt_to_html(plt_fig=None, transparent=True, dash_html=None)

  • Returns base64 encoded Image to display in notebook or HTML or plotly's dash_html_components.Img object.
  • Parameters
    • plt_fig : Matplotlib's figure instance, auto picks as well.
    • transparent: True of False for fig background.
    • dash_html : Default is None which results in an image display in jupyter notebook.
      • If True, returns html.Img object for plotly's dash.
      • If False, returns object to embed in HTML DOM.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
import pivotpy as pp 
import matplotlib.pyplot as plt
pp.quick_bplot("E:/Research/graphene_example/ISPIN_1/bands/vasprun.xml",elim=[-9,9]);
fig = plt_to_html(dash_html=None,transparent=False)
fig
{% endraw %}

Below code snippest could be used to inclue svg in html document from a figure.

data = plt_to_html(dash_html=False)
html_str= """
<!DOCTYPE html>
<head></head>
<body>
    <div>
    {}
    </div>
</body>
""".format(data)

with open('fig.html','w') as f:
    f.write(html_str)
f.close()
{% raw %}

  Index 
  XmlElementTree 
  StaticPlots● 
  InteractivePlots 
  Utilities 
  StructureIO 
  Widgets 

{% endraw %}